<?php

namespace App\Lib;
class Redis
{
    // redis 配置
    public static $redis                = [] ;
    public static $redis_driver_default = 'redis_cluster' ; // redis_cluster redis
    public static $rconf                = [
        'REDIS_HOST'    => '127.0.0.1' ,
        'REDIS_PORT'    => '6379' ,
        'REDIS_PWD'     => '' ,
    ] ;
    public static $rconf_c  = [
        'SERVERS'       => [
            '192.168.200.228:7000' ,
            '192.168.200.228:7001' ,
            '192.168.200.228:7002'
        ],
        'REDIS_PWD'     => '' ,
    ] ;

    /* 
    use \app\lib\redis;
    $redis = redis::init()->set('name','value');
    echo redis::init()->get('name');

    $redis = \app\lib\redis::init()->set('name','value');
    echo \app\lib\redis::init()->get('name');
    */
    public static function init($driver='') {
        if ( empty( self::$redis ) ) {
            if ( empty( $driver ) ) {
                $driver = self::$redis_driver_default ;
            }
            // echo 'init'."\r\n";
            return self::$driver() ;
        }else{
            // echo 'getstatic'."\r\n";
        }
        return self::$redis;
    }

    // redis 单机
    public static function redis() { // private
        if ( empty( self::$redis ) ) {
            if ( !extension_loaded('redis') ) {
                throw new \RedisException('not support: redis');
            }
            $redis = new \Redis();
            $redis->pconnect( self::$rconf['REDIS_HOST'] ,  self::$rconf['REDIS_PORT'] );
            if (  self::$rconf['REDIS_PWD'] ) {
                $redis->auth( self::$rconf['REDIS_PWD'] );
            }
            try {
                $response = $redis->ping();
                if ($response != '+PONG') {
                    throw new \RedisException('This connection is down');
                }
            } catch (\RedisException $e) {
                die('{"fail":"KV服务连接失败"}');
            }
            if ($db !== false) {
                $redis->select(intval($db));
            }
            self::$redis    = $redis ;
            //echo 'init'."\r\n";
        }else{
            //echo 'getstatic'."\r\n";
        }
        return self::$redis;
    }

    // redis 集群
    public static function redis_cluster(){
        if ( empty( self::$redis ) ) {
            try {
                if ( !extension_loaded('redis') ) {
                    throw new \RedisException('not support: redis');
                }
                $redis = new \RedisCluster( null , self::$rconf_c['SERVERS'] );
                if (  self::$rconf_c    ['REDIS_PWD'] ) {
                    $redis->auth( self::$rconf_c['REDIS_PWD'] );
                }
            } catch (\RedisException $e) {
                die('{"fail":"KV服务连接失败"}');
            }
            self::$redis    = $redis ;
            //echo 'init'."\r\n";
        }else{
            //echo 'getstatic'."\r\n";
        }
        return self::$redis;
    }
}